<template>
  <div>
    <div style="font-size:18px;">权限管理</div>
    <hr>
    <br>
<!--   <el-tabs v-model="activeName" @tab-click="handleClick">
    <el-tab-pane label="用户管理" name="first">
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="0px" class="demo-ruleForm" style="float: left;">
            <el-form-item prop="username" class="input_edit" >
               <el-input v-model="ruleForm.username" placeholder="账号/手机"  ></el-input>
            </el-form-item>
            <el-form-item prop="acount" class="input_edit" >
               <el-input v-model="ruleForm.acount" placeholder="姓名"  ></el-input>
            </el-form-item>
             <el-form-item prop="roleId" class="input_edit" >
                <el-select v-model="ruleForm.roleId" placeholder="请选择角色" clearable>
                <el-option
                  v-for="item in roleOptions"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <div class="login-btn" style="float: left">
                <el-button type="primary" @click="searchUser()">搜索</el-button>
            </div>
        </el-form>
        <div style="float: right">
            <el-button @click="freezeUser(1)" type="danger">冻结用户</el-button>
            <el-button @click="freezeUser(0)" >启用用户</el-button>
            <el-button @click="stopCommon(1)" type="danger">用户禁言</el-button>
            <el-button @click="stopCommon(0)" >解除禁言</el-button>
        </div>
        <el-table :data="userData" border @selection-change="handleSelectionChange" >
            <el-table-column type="selection" width="80px" ></el-table-column>
            <el-table-column prop="realName" label="姓名" width="100px" ></el-table-column>
            <el-table-column label="性别" width="80px">
                 <template scope="scope">
                     <div v-if="scope.row.sex == '1'">男</div>
                     <div v-if="scope.row.sex == '-1'">女</div>
                 </template>
             </el-table-column>
            <el-table-column prop="username" label="手机号" width="140px" ></el-table-column>
            <el-table-column  label="头像"width="140px">
                <template scope="scope">
                    <img :src="scope.row.headIcon" width="100px" height="100">
                </template>
            </el-table-column>
            <el-table-column prop="birthday" label="生日"  width="120px" :formatter="formatterBirthday"></el-table-column>
            <el-table-column prop="email" label="邮箱" width="220px" ></el-table-column>
            <el-table-column prop="score" label="积分" width="120px" ></el-table-column>
             <el-table-column prop="roleName" label="角色" width="100px" ></el-table-column>
            <el-table-column prop="createDate" width="160px"  label="创建时间" :formatter="formatterCreateDate" ></el-table-column>
             <el-table-column label="禁言" width="80px" >
                 <template scope="scope">
                     <div v-if="scope.row.isComment == '0'" >正常</div>
                     <div v-if="scope.row.isComment == '1'">禁言</div>
                 </template>
             </el-table-column>
             <el-table-column label="状态" width="80px">
                 <template scope="scope">
                     <div v-if="scope.row.status == '1'">冻结</div>
                     <div v-if="scope.row.status == '0'">启用</div>
                 </template>
             </el-table-column>
             <el-table-column label="操作" width="150px">
                <template scope="scope">
                    <el-button size="small"  type="danger" @click="stopCommon(1,scope.row.id,scope.row,scope.$index)"  v-if="scope.row.isComment == '0'" >禁言</el-button>
                    <el-button size="small" @click="stopCommon(0, scope.row.id,scope.row,scope.$index)"  v-if="scope.row.isComment == '1'" >可言</el-button>
                    <el-button size="small" @click="freezeUser(0,scope.row.id,scope.row,scope.$index)"  v-if="scope.row.status == '1'" >启用</el-button>
                    <el-button size="small" type="danger" @click="freezeUser(1, scope.row.id,scope.row,scope.$index)"  v-if="scope.row.status == '0'" >冻结</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-sizes="[10, 20, 50]"
              :page-size="page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </div>
    </el-tab-pane>
    <el-tab-pane label="角色管理" name="second">
        <div style="float: right">
            <el-button @click="editRole()" type="danger">添加角色</el-button>
        </div>
        <el-table :data="roleData" border style="width: 100%"  >
            <el-table-column prop="name" label="角色名称" ></el-table-column>
             <el-table-column label="操作" >
                <template scope="scope">
                    <el-button size="small" @click="editRole(scope.row)">修改信息</el-button>
                    <el-button size="small" @click="editRolePrivilege(scope.row)">修改权限</el-button>
                </template>
             </el-table-column>
        </el-table>
        <el-dialog title="修改角色权限" :visible.sync="dialogFormVisible" >
             <div style="text-align:center;">
                <div style="text-align:left;width:480px;margin:0 auto;">
                    <div style="line-height:30px;">权限 <span style="color:red;">{{rolePriName}}</span> 修改</div>
                      <el-tree :data="rpTreeValue" ref="rpTree"
                        show-checkbox
                        node-key="id"
                        :default-expanded-keys="[]"
                        :default-checked-keys="[]"
                        :props="defaultProps">
                      </el-tree>
                    </div>
              </div>
          <div slot="footer" class="dialog-footer">
            <el-button @click="dialogFormVisible = false">取 消</el-button>
            <el-button type="primary" @click="saveRolePrivilege()">保 存</el-button>
          </div>
        </el-dialog>
    </el-tab-pane>
    <el-tab-pane label="权限管理" name="third">-->
         <!-- <el-form :model="ruleForm2" ref="ruleForm2" label-width="0px" class="demo-ruleForm" style="float: left;">
                <el-form-item prop="pname" class="input_edit" >
                   <el-input v-model="ruleForm2.pname" placeholder="权限名称"  ></el-input>
                </el-form-item>
                <el-form-item prop="paddress" class="input_edit" >
                   <el-input v-model="ruleForm2.paddress" placeholder="权限链接"  ></el-input>
                </el-form-item>

            <div class="login-btn" style="float: left">
                <el-button type="primary" @click="searchUser()">搜索</el-button>
            </div>
        </el-form> -->
        <div style="float: right">
            <el-button @click="resetForm3();priDialogFormVisible=true;" >添加权限</el-button>
            <el-button @click="deletePrivilege()" type="danger">删除权限</el-button>
        </div>
        <el-table :data="priData" border style="width: 100%" @selection-change="priHandleSelectionChange" >
            <el-table-column type="selection" width="auto" ></el-table-column>
            <el-table-column prop="name" label="名称" ></el-table-column>
            <el-table-column prop="address" label="链接" ></el-table-column>
             <el-table-column label="操作" >
                <template scope="scope">
                    <el-button size="small" @click="resetForm3();editPrivilege(scope.row,scope.$index)" >修改信息</el-button>
                    <el-button size="small" type="danger" @click="deletePrivilege(scope.row.id,scope.$index)" >删除信息</el-button>
                </template>
            </el-table-column>
        </el-table>
        <div class="pagination">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :page-sizes="[10, 20, 50]"
              :page-size="page_size"
              layout="total, sizes, prev, pager, next, jumper"
              :total="total">
            </el-pagination>
        </div>

        <el-dialog :title="priName" :visible.sync="priDialogFormVisible"  >
            <div style="text-align:center;">
                <div style="text-align:left;width:600px;margin:0 auto;">
                    <el-form :model="ruleForm3" :rules="rules3" ref="ruleForm3" label-width="100px" class="demo-ruleForm" style="width:60%;" >
                         <el-form-item prop="id"  style="display:none;" label="权限名称">
                           <el-input v-model="ruleForm3.id" placeholder=""  ></el-input>
                        </el-form-item>
                        <el-form-item prop="name" label="权限名称">
                           <el-input v-model="ruleForm3.name" placeholder=""  ></el-input>
                        </el-form-item>
                        <!-- <el-form-item prop="isMenu" label="类型" >
                           <el-select v-model="ruleForm3.isMenu" placeholder="" @change="changePri">
                            <el-option key="0" label="权限" value="0" ></el-option>
                            <el-option key="1" label="权限目录" value="1"></el-option>
                          </el-select>
                        </el-form-item> -->
                        <el-form-item prop="address" label="权限链接" v-show='priUrl' >
                           <el-input v-model="ruleForm3.address" placeholder=""  ></el-input>
                        </el-form-item>
                        <el-form-item prop="pid" label="父目录" >
                            <div>当前选中:<span style="color:#ff1100;">{{priPName}}</span><span v-show="priCleanShow" @click="cleanPri">清除</span></div>
                           <el-tree :data="priTree" node-key="id" :default-expanded-keys="[]" :default-checked-keys="[]" :props="defaultProps" @node-click="checkChange" ref="tree2" ></el-tree>
                        </el-form-item>
                        <el-form-item prop="remark" label="备注" >
                           <el-input type="textarea" v-model="ruleForm3.remark" placeholder=""  ></el-input>
                        </el-form-item>
                    </el-form>  
                </div>
            </div>
            <div style="clear:both;"></div>
            <div slot="footer" class="dialog-footer">
                <el-button @click="priDialogFormVisible=false">取消</el-button>
                <el-button type="primary" @click="updatePrivilege()">保存</el-button>
            </div>
        </el-dialog>


<!--     </el-tab-pane>
  </el-tabs> -->
  </div>
</template>
<script>
    import $ from 'jquery';
    import Vue from 'vue';

  export default {
    data() {
        return {
            activeName: 'first',
            userData: [],
            roleData:[],
            priData:[],

            cur_page: 1,
            page_size:10,
            total:0,
            multipleSelection: [],

            ruleForm: {
                username: '',
                acount: '',
                roleId:''
            },
            roleOptions:[],
            ruleForm2:{
                pname:'',
                paddress:''
            },
            ruleForm3:{
                id:'',
                name:'',
                isMenu:'0',
                address:'',
                pid:'',
                remark:''
            },
            rules: {
                username: [],
            },
            rules3: {
                name: [
                    {required: true, message: '请输入权限名', trigger: 'blur'}
                ],

                address: [
                    { trigger: 'blur',validator: this.validatePriUrl}
                ],
                
            },
            searchUrl:"/user/list",
            searchData:{},
            table:'userData',

            dialogFormVisible:false,

            rolePriData:{},
            rolePriValue:{},
            rolePriName:'',
            rolePriTitle:['未选择','已选择'],
            rolePriId:'',

            priMultipleSelection:[],
            priDialogFormVisible:false,

            priName:'添加权限',
            priCleanShow:false,
            priTree:[],
            priBTree:[],
            priPName:'',//选中父id的名字
            defaultProps: {
              children: 'children',
              label: 'name'
            },
            priUrl:true,
            rpTreeValue:{},
        };
    },
    created(){
        var self=this;

        self.searchUrl="/privilege/list";
        self.priData=[];
        self.table='priData';

        self.getData();
        self.myajax("/role/list",{pageSize:1000},function(data){
            self.roleOptions=data.data.list;
        });
    },
    methods: {
        searchUser(){
            this.cur_page=1;
            this.getData();
        },
        handleClick(tab, event) {
            var self=this;
            //标签点击事件
            //console.log(tab, event);
            var tabname=tab.name;
            self.cur_page=1;
            self.total=0;
            if(tabname=='first'){
                self.searchUrl="/user/list";
                self.userData=[];
                self.table='userData';
            }else if(tabname=='second'){
                self.searchUrl="/role/list";
                self.userData=[];
                self.table='roleData';
            }else if(tabname=='third'){
                self.searchUrl="/privilege/list";
                self.priData=[];
                self.table='priData';
            }else{

            }
            self.getData();
        },
        handleCurrentChange(val){//翻页
            this.cur_page = val;
            this.getData();
        },
        handleSizeChange(val) {//每页数量
            this.page_size=val;
            this.getData();
        },
        getData(){
            let self = this;
            var data=self.searchData;
            data.pageSize=self.page_size
            data.pageNumber=self.cur_page;
            data.param=new Object();
            data.param.username=self.ruleForm.username;
            data.param.realName=self.ruleForm.acount;
            data.param.roleId=self.ruleForm.roleId;
            data.param.pname=self.ruleForm2.pname;
            data.param.paddress=self.ruleForm2.paddress;
             self.myajax(self.searchUrl,data,function(data){
                    //console.log(data)
                   self[self.table]=data.data.list;
                   self['total']=data.data.total;
            });
           /* this.$axios.post(self.$host+"/user/list",{page:self.cur_page,token:token}).then((res) => {
                console.log(res.data);
                //self.userData = res.data.data;
            })*/
        },
        formatter(row, column) {
            return row.address;
        },
        formatterCreateDate(row,column){
            var date = row.createDate;  
              if (date == undefined) {  
                 return "";  
              } 
              return new Date(date).format("yyyy-MM-dd h:m");
        },
        formatterBirthday(row,column){
            var date = row.birthday;  
              if (date == undefined) {  
                 return "";  
              } 
              return new Date(date).format("yyyy-MM-dd");
        },
        filterTag(value, row) {
            return row.tag === value;
        },
        handleEdit(index, row) {
            this.$message('编辑第'+(index+1)+'行');
        },
        handleDelete(index, row) {
            this.$message.error('删除第'+(index+1)+'行');
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
        },
        freezeUser(type,id){//冻结解冻用户
            var self=this;
            if(type!=0&&type!=1){
                self.$notify({title: '提示',message: '传入类型不正确',type: 'warning'});
                return;
            }
            var ids=new Array();
             if(id){
                ids.push(id);
            }else{
                if(self.multipleSelection.length==0){
                    self.$notify({title: '提示',message: '请先选择用户',type: 'warning'});
                    return;
                }
                for(var k in this.multipleSelection){
                    ids.push(this.multipleSelection[k].id);
                }
            }
            self.$confirm('确定要'+(type==0?"启用用户":"冻结用户")+', 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              var data={type:type,uids:ids};
              self.myajax("/user/freeze",data,function(data){
                    var code=data.code;
                    if(code==2000){
                        self.$notify({title: '提示',message: (type==0?"启用用户":"冻结用户")+"成功",type: 'success'});
                    }else if(code==2001){
                        self.$notify({title: '提示',message:"传入类型不正确",type: 'error'});
                    }else if(code==2002){
                        self.$notify({title: '提示',message:"没有用户信息",type: 'error'});
                    }
                    self.getData();

              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              });          
            });
        },
        stopCommon(type,id){//禁言.解除禁言
             var self=this;
            if(type!=0&&type!=1){
                self.$notify({title: '提示',message: '传入类型不正确',type: 'warning'});
                return;
            }
            var ids=new Array();
             if(id){
                ids.push(id);
            }else{
                if(self.multipleSelection.length==0){
                    self.$notify({title: '提示',message: '请先选择用户',type: 'warning'});
                    return;
                }
                for(var k in this.multipleSelection){
                    ids.push(this.multipleSelection[k].id);
                }
            }
            self.$confirm('确定要'+(type==1?"用户禁言":"解除禁言")+', 是否继续?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              var data={type:type,uids:ids};
              self.myajax("/user/comment",data,function(data){
                    var code=data.code;
                    if(code==2000){
                        self.$notify({title: '提示',message: (type==1?"用户禁言":"解除禁言")+"成功",type: 'success'});
                    }else if(code==2001){
                        self.$notify({title: '提示',message:"传入类型不正确",type: 'error'});
                    }else if(code==2002){
                        self.$notify({title: '提示',message:"没有用户信息",type: 'error'});
                    }
                    self.getData();

              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              });          
            });
        },
        editRole(row){//添加修改角色
            var self=this;
            var title=""
            if(row){
              title="修改角色信息"
            }else{
              title="添加角色信息"
            }
            
            this.$prompt('请输角色名称', title, {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              //inputPattern: /[\w!#$%&'*+/=?^_`{|}~-]+(?:\.[\w!#$%&'*+/=?^_`{|}~-]+)*@(?:[\w](?:[\w-]*[\w])?\.)+[\w](?:[\w-]*[\w])?/,
              inputPattern:/.+/,
              inputValue:(row?row.name:''),
              inputErrorMessage: '会员名不能为空'
            }).then(({ value }) => {
                var url="/role/add";
                var data={name:value};
                if(row){
                    url="/role/update"
                    data.id=row.id;
                }
              self.myajax(url,data,function(data){
                    var code=data.code;
                    if(code==1000){
                        self.$notify({title: '提示',message:"修改成功",type: 'success'});
                    }else{
                        self.$notify({title: '提示',message: data.msg,type: 'waring'});
                    }
                    self.getData();
              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '取消输入'
              });       
            });
        },
/*        editRolePrivilege(row){
            var self=this;

            self.rolePriId=row.id;
            self.rolePriName=row.name;
            var rid=row.id;
            var data={rid:rid};
            self.myajax("/privilege/list",{pageSize:1000},function(pdata){//取得所有
                self.dialogFormVisible=true;
                self.rolePriData=pdata.data;
                self.myajax("/role/getPrivilegeByRoleId",data,function(data){
                    var bdata=data.data;
                    var values=new Array();
                   if(bdata){
                        for(var k in bdata){
                            values.push(bdata[k].id);
                        }
                   }
                   self.rolePriValue=values;
                });
            });
        },*/
        editRolePrivilege(row){
          
          var self=this;

          self.rolePriId=row.id;
          self.rolePriName=row.name;
          var rid=row.id;
          var data={rid:rid};
          self.myajax("/privilege/list",{pageSize:1000},function(pdata){//取得所有
              self.dialogFormVisible=true;
              self.rpTreeValue=self.beTree(pdata.data.list);
              self.myajax("/role/getPrivilegeByRoleId",data,function(data){
                  var bdata=data.data;
                  var values=new Array();
                  console.log(bdata);
                  if(bdata){
                      for(var k in bdata){
                          values.push(bdata[k].id);
                      }
                  }
                 console.log(values);
                 //console.log(self.$refs.rpTree);
                 Vue.nextTick(function(){
                    self.$refs.rpTree.setCheckedKeys(values);
                 })
                 
              });
          });
        },
        saveRolePrivilege(rid){//保存角色的权限
            var self=this;
            var rid=self.rolePriId;
            //var pids=self.rolePriValue;
            var pids=self.$refs.rpTree.getCheckedKeys();
            var data={rid:rid,pids:pids};
            self.myajax("/role/updatePrivilege",data,function(data){
                self.$notify({title: '提示',message:"修改成功",type: 'success'});
                self.dialogFormVisible = false;
            });
        },
        editPrivilege(row){
            var self=this;


            self.priName="修改权限信息"
            this.ruleForm3.id=row.id;
            this.ruleForm3.name=row.name;
            this.ruleForm3.address=row.address;
            this.ruleForm3.remark=row.remark;
            this.ruleForm3.isMenu=row.isMenu+"";
            if(!row.isMenu)
              this.ruleForm3.isMenu="0";
            this.ruleForm3.pid=row.pid;
            var btree=self.priBTree;
            if(btree&&row.pid){
              for(var k in btree){
                if(btree[k].id==row.pid){
                  self.priPName=btree[k].name;
                  self.priCleanShow=true;
                  self.priBTree.splice(k,1);
                  self.deleteTreeById(self.priTree,row.id);
                }
              }
            }
            self.changePri();
            self.priDialogFormVisible = true;
        },
        updatePrivilege(){
            var self=this;
            this.$refs['ruleForm3'].validate((valid) => {
              if(valid){
                var data={};
                var id=self.ruleForm3.id;
                data.name=self.ruleForm3.name;
                data.address=self.ruleForm3.address;
                data.remark=self.ruleForm3.remark;
                data.isMenu=self.ruleForm3.isMenu+"";
                data.pid=self.ruleForm3.pid;
                var url="/privilege/create";
                if(id){
                    url="/privilege/update";
                    data.id=id;
                }

                self.myajax(url,data,function(data){
                    self.$notify({title: '提示',message:"修改成功",type: 'success'});
                    self.priDialogFormVisible = false;
                });
                this.getData();
              }
            });
        },
        deletePrivilege(id){//禁言.解除禁言
            var self=this;
            var ids=new Array();
             if(id){
                ids.push(id);
            }else{
                if(self.priMultipleSelection.length==0){
                    self.$notify({title: '提示',message: '请先选择权限',type: 'warning'});
                    return;
                }
                for(var k in this.priMultipleSelection){
                    ids.push(this.priMultipleSelection[k].id);
                }
            }
            self.$confirm('确定要删除权限?', '提示', {
              confirmButtonText: '确定',
              cancelButtonText: '取消',
              type: 'warning'
            }).then(() => {
              var data={ids:ids,test:'1'};
              self.myajax("/privilege/delete",data,function(data){
                    var code=data.code;
                    if(code==1000){
                        self.$notify({title: '提示',message: "删除成功",type: 'success'});
                    }else if(code==2004){
                        self.$notify({title: '提示',message:"没有订单信息",type: 'error'});
                    }
                    self.getData();

              });
            }).catch(() => {
              this.$message({
                type: 'info',
                message: '已取消操作'
              });          
            });
        },
        priHandleSelectionChange(val) {
            this.priMultipleSelection = val;
        },
        resetForm3(formName) {
          var self=this;

          
          var data=self.searchData;
          data.pageSize=1000;
          data.pageNumber=1;
          data.param=new Object();
          data.param.isMenu="1";
          self.myajax(self.searchUrl,data,function(data){
                  //console.log(data)
                  if(data.data.list){
                   self.priTree=data.data.list;
                   self.priBTree=new Array().concat(data.data.list);
                   self.beTree(self.priTree);
                 }else{
                   self.priTree=[];
                   self.priBTree=[];
                 }
          },true);

          this.priName="添加权限信息"
          this.ruleForm3.id='';
          this.ruleForm3.name='';
          this.ruleForm3.address='';
          this.ruleForm3.remark='';
          this.ruleForm3.isMenu="0";
          this.ruleForm3.pid="";
          this.priPName="";
          self.priCleanShow=false;
          self.changePri();
        },
        checkChange(p1,p2,p3){
          var self=this;
          var pid=p1.pid;
          this.ruleForm3.pid=p1.id;
          this.priPName=p1.name;
          self.priCleanShow=true;
        },
        beTree(data){
          for(var k in data){
            var bdata=data[k];
            var id=bdata.id;
            genTree(id,bdata,data);
          }
          function genTree(pid,bdata,data){
            for(var k in data){
              var gdata=data[k];
              if(gdata.pid&&gdata.pid==pid&&pid!=gdata.id){
                gdata.self_issub=true;
                if(bdata.children){
                  bdata.children.push(gdata);
                }else{
                  bdata.children=new Array();
                  bdata.children.push(gdata);
                }
              }
            }
          }
          for(var i=data.length-1;i>=0;i--){
            var bdata=data[i];
            if(bdata.self_issub){
              data.splice(i,1);
            }
          }
          return data;
        },
        deleteTreeById(tree,id){
          for(var k in tree){
            var btree=tree[k];
            if(btree.id==id){
              tree.splice(i,1);
            }
          }
        },
        changePri(){
          var self=this;
          var par=self.ruleForm3.isMenu;
          if(par=='1'){
            self.priUrl=false;
          }else{
            self.priUrl=true;
          }
        },
        cleanPri(){
          var self=this;
          self.ruleForm3.pid='';
          self.priPName='';
          self.priCleanShow=false;
        },
        validatePriUrl(rule, value, callback){
          var self=this;
          var par=self.ruleForm3.isMenu;
          if(par=='1'){
            self.ruleForm3.address=''
            callback();
          }else{
            //if(self.ruleForm3.address=='')
             // callback(new Error('请输入权限链接'));
             callback();
          }
        }
    }
  };
</script>
<style scoped>
    .input_edit{
        width: 200px;
        float: left;
        margin-right:10px;
    }
    .cell{
        padding: 0 5px !important;
        overflow: auto;
    }
</style>
